class ResourceController {

    def newResourceProcess
    def fetchFeedProcess
    def taskExecutor
    def indexService
    
    def index = { redirect(action:list,params:params) }

    // the delete, save and update actions only accept POST requests
    def static allowedMethods = [delete:'POST', save:'POST', update:'POST']

    def list = {
        if(!params.max) params.max = 10
        [ resourceList: Resource.list( params ) ]
    }

    def show = {
        def resource = Resource.get( params.id )

        if(!resource) {
            flash.message = "Resource not found with id ${params.id}"
            redirect(action:list)
        }
        else { return [ resource : resource ] }
    }

    def delete = {
        def resource = Resource.get( params.id )
        if(resource) {
            resource.entries.each { indexService.removeIndex(it.id) }
            resource.delete()
            flash.message = "Resource ${params.id} deleted"
            redirect(action:list)
        }
        else {
            flash.message = "Resource not found with id ${params.id}"
            redirect(action:list)
        }
    }

    def edit = {
        def resource = Resource.get( params.id )

        if(!resource) {
            flash.message = "Resource not found with id ${params.id}"
            redirect(action:list)
        }
        else {
            return [ resource : resource ]
        }
    }

    def update = {
        def resource = Resource.get( params.id )
        if(resource) {
            resource.properties = params
            if(!resource.hasErrors() && resource.save()) {
                flash.message = "Resource ${params.id} updated"
                redirect(action:show,id:resource.id)
            }
            else {
                render(view:'edit',model:[resource:resource])
            }
        }
        else {
            flash.message = "Resource not found with id ${params.id}"
            redirect(action:edit,id:params.id)
        }
    }

    def ping = {
        def resource = Resource.get( params.id )
        if(!resource) {
            flash.message = "Resource not found with id ${params.id}"
            redirect(action:list)
        }
        fetchFeedProcess.resource = resource
        taskExecutor.execute(fetchFeedProcess)
        redirect(action:list)
    }

    def create = {
        def resource = new Resource()
        resource.properties = params
        return ['resource':resource]
    }

    def fetchAsync = {
        newResourceProcess.url = params.url
        println newResourceProcess.url
        taskExecutor.execute(newResourceProcess)
        redirect(action:list)
    }

    def save = {
        def resource = new Resource(params)
        if(!resource.hasErrors() && resource.save()) {
            flash.message = "Resource ${resource.id} created"
            redirect(action:show,id:resource.id)
        }
        else {
            render(view:'create',model:[resource:resource])
        }
    }
}
